using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Resources;
using System.Collections;
using System.Threading;
using System.Data.OleDb;


namespace Rally_Dekstop
{
    
    public partial class frmReviewEditTestCases : Form
    {
        private enum TestCaseEditorMode{ViewMode,
                                 EditMode,
                                 BulkMode,
                                 ReviewMode,
                                 WhileUpdate}
        private TestCaseEditorMode PresentMode;
        private ResourceManager m_ResourceManager = Localizer.getInstance().GetResourceManager();
        
        private object parent = null;
        private bool dataupdated = false;
        private string filename;
        private bool saveAsFlag = false;

        IRallyService service = null;
        
        //testcasehash stores all the testcases fetched from rally for the workproduct
        private Hashtable testCaseHash = new Hashtable();
        
        //store the updated testcase
        private Hashtable updatedTestCases = new Hashtable();

        //to store review comments
        private Hashtable reviewComments = new Hashtable();


       
        //displayed defect id
        private string displayedID;
        
        //variable used to populate the list view
        string[] testcaseitem = new string[4];

        //variables used for threading
            //for fetaching test cases rally
            private ArrayList threadResult;
            private string toThreadIDText;
            private string toThreadTypeFinal;
            

            //for updating test cases to rally
            TestCase TestCaseOnThread = new TestCase();
            string TestCaseUpdateResult;
            
            //for deleting testcases from rally
            string testCaseToDeleteID = string.Empty;
            string testCaseDeleteResult = string.Empty;



        public frmReviewEditTestCases(Object listener)
        {
            InitializeComponent();
            parent = listener;

            int i = 0;
            for (i = 0; i < RallyDesk.CURRENTWORKSPACE.WorkSpaceSpecifics.TestCase.Types.Count; i++)
            {
                this.cmb_TestCaseType.Items.Add(RallyDesk.CURRENTWORKSPACE.WorkSpaceSpecifics.TestCase.Types[i]);
            }
            for (i = 0; i < RallyDesk.CURRENTWORKSPACE.WorkSpaceSpecifics.TestCase.Priority.Count; i++)
            {
                this.cmb_TestCasePriority.Items.Add(RallyDesk.CURRENTWORKSPACE.WorkSpaceSpecifics.TestCase.Priority[i]);
            }
            for (i = 0; i < RallyDesk.CURRENTWORKSPACE.WorkSpaceSpecifics.TestCase.Method.Count; i++)
            {
                this.cmb_TestCaseMethods.Items.Add(RallyDesk.CURRENTWORKSPACE.WorkSpaceSpecifics.TestCase.Method[i]);
            }
            for (i = 0; i < RallyDesk.CURRENTWORKSPACE.WorkSpaceSpecifics.TestCase.Risk.Count; i++)
            {
                this.cmb_TestCaseRisks.Items.Add(RallyDesk.CURRENTWORKSPACE.WorkSpaceSpecifics.TestCase.Risk[i]);
            }
            for (i = 0; i < RallyDesk.CURRENTWORKSPACE.WorkSpaceSpecifics.TestCase.Package.Count; i++)
            {
                this.cmb_TestCasePackage.Items.Add(RallyDesk.CURRENTWORKSPACE.WorkSpaceSpecifics.TestCase.Package[i]);
            }


            listView_testcases.Columns.Add("ID", 80);
            listView_testcases.Columns.Add("Name",500);
            listView_testcases.Columns.Add("Updated", 80);
            listView_testcases.Columns.Add("Review Comments", 160);

            if (RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceType == "UseCase")
            {
                this.workproduct_comboBox.Items.Add("Use Case");
                this.workproduct_comboBox.Items.Add("Feature");
                this.workproduct_comboBox.Items.Add("Supplemental Requirement");
                this.workproduct_comboBox.Items.Add("Story");
                this.workproduct_comboBox.Items.Add("Defect");
            }
            else if (RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceType == "UserStory")
            {
                this.workproduct_comboBox.Items.Add("User Story");

            }
            
            htmlEditor_Review.IsEditMode = true;
            this.MdiParent = Rally_Dekstop.Program.RallyMain;
            SetModeOFEditor(TestCaseEditorMode.ViewMode);

        }

        private void GUITestCaseEditor_Load(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
        }
        private void ThreadGetTestCases()
        {
            if (service == null)
            {
                if (RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceType == "UseCase")
                {
                    service = new RallyAPIUseCase(RallyDesk.url);
                }
                else
                {
                    service = new RallyAPIUserStory(RallyDesk.url);
                }
            }
            threadResult = service.GetTestCasePerWorkProduct(toThreadTypeFinal, toThreadIDText);

        }
        private void gettestcases_button_Click(object sender, EventArgs e)
        {
           try
            {
                SetModeOFEditor(TestCaseEditorMode.WhileUpdate);


                if (listView_testcases.Items.Count > 0)

                    if (MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/DeleteAllRecordsWarning"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
                        return;
                int i = 0;
                close_Template();

                RecNum_label.Text = "";
                //IRallyService service = null;
                dataupdated = false;

                ArrayList result = new ArrayList();

                string typefinal;
                string type = this.workproduct_comboBox.Text.ToLower();

                if (this.workproduct_comboBox.Text == "User Story")
                {
                    typefinal = "hierarchicalrequirement";
                    //  service = new RallyAPIUserStory(RallyDesk.url); 
                }
                else
                {
                    //  service = new RallyAPIUseCase(RallyDesk.url);
                    string type2 = type.Trim();
                    typefinal = type2.Replace(" ", "");

                }

                toThreadIDText = this.SR_ID.Text;
                toThreadTypeFinal = typefinal;

                Thread toRunService = new Thread(new ThreadStart(ThreadGetTestCases));
                toRunService.Start();

                ((RallyDesk)parent).toolStripStatusLabel.Text = "Fetching Test Cases..";
                ((RallyDesk)parent).ProgressBarMain.Style = ProgressBarStyle.Marquee;
                ((RallyDesk)parent).ProgressBarMain.Visible = true;

                while (toRunService.IsAlive)
                {

                    Application.DoEvents();
                }

                toRunService.Abort();
               ((RallyDesk)parent).ProgressBarMain.Visible = false;
               ((RallyDesk)parent).toolStripStatusLabel.Text = "Ready";


                result = threadResult;
                if (result == null)
                {
                    MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/ValidWorkProduct"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;

                }
                if (result.Count > 0)
                {


                    System.Windows.Forms.ListViewItem listViewItem1 = new System.Windows.Forms.ListViewItem();
                    string[] NewItem = new string[6];
                    string key;
                    for (i = 0; i < result.Count; i++)
                    {
                        key = ((TestCase)result[i]).ID;
                        
                        if (!testCaseHash.Contains(key))
                            testCaseHash.Add(key, result[i]);
                        else
                            testCaseHash[key] = result[i];

                        
                    }

                     RecNum_label.Text = Convert.ToString(testCaseHash.Count);
                    
                }
                else
                {
                    MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/NoTestCasesInWorkProduct"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }

            finally
            {
               SetModeOFEditor(TestCaseEditorMode.ViewMode);
            }

        
        }
        private void populateTestCaseList()
        {
            listView_testcases.Items.Clear();
            if(testCaseHash.Count > 0)
            {
                foreach (TestCase tc in testCaseHash.Values)
                {
                    System.Windows.Forms.ListViewItem listViewItem1 = new System.Windows.Forms.ListViewItem();
                    testcaseitem[0] = tc.ID;
                    testcaseitem[1] = tc.Name;
                    if (updatedTestCases.Contains(tc.ID))
                    {
                        testcaseitem[2] = "True"; //updated
                    }
                    else
                    {
                        testcaseitem[2] = ""; //updated
                    }
                    if (reviewComments.Contains(tc.ID))
                    {
                        testcaseitem[3] = "True"; //updated
                    }
                    else
                    {
                        testcaseitem[3] = ""; //updated
                    }


                    listViewItem1 = new System.Windows.Forms.ListViewItem(testcaseitem, -1);
                    this.listView_testcases.Items.AddRange(new System.Windows.Forms.ListViewItem[] {
                        listViewItem1});
                }
            }
        }

        private void listView_testcases_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.listView_testcases.Items.Count > 0)
            {
                if (this.listView_testcases.CheckedItems.Count < this.listView_testcases.Items.Count)
                {
                    SelectAll_checkBox.CheckState = CheckState.Unchecked;
                    SelectAll_checkBox.Enabled = true;
                }
                else
                    SelectAll_checkBox.Enabled = false;

            }
            if (this.listView_testcases.SelectedItems.Count > 0)
            {

                foreach (ListViewItem tcitem in this.listView_testcases.SelectedItems)
                {

                    populateTestCaseOnForm(tcitem.SubItems[0].Text);
                    break;

                }

            }
        }

        private void populateTestCaseOnForm(string tcid)
        {
            TestCase tc = new TestCase();

            //shall display the updated record
            if (updatedTestCases.Contains(tcid))
            {
                tc = ((TestCase)(updatedTestCases[tcid]));
            }
            else
            {
                if(testCaseHash.Contains(tcid))
                tc = ((TestCase)(testCaseHash[tcid]));
            }
                
            if (tc.ID != string.Empty)
            {
                    this.txt_name.Text = tc.Name;
                    this.txt_notes.Text = tc.Notes;
                    this.txt_objective.Text = tc.Objective;
                    this.cmb_TestCaseType.Text = tc.Type;
                    this.cmb_TestCaseMethods.Text = tc.Method;
                    this.cmb_TestCasePriority.Text = tc.Priority;
                    this.cmb_TestCaseRisks.Text = tc.Risk;
                    this.cmb_TestCasePackage.Text = tc.Package;
                    this.txt_preConditions.Text = tc.PreConditions;
                    this.txt_postConditions.Text = tc.PostConditions;
                    this.txt_Owner.Text = tc.Owner;
                    htmlEditor_Desc.HTMLText = "<html>" + tc.Description + "</html>";
                    htmlEditor_Validation.HTMLText = "<html>" + tc.ValidationInput + "</html>";
                    htmlEditor_Expected.HTMLText = "<html>" + tc.ValidationExpectedResult + "</html>";

                    if (PresentMode == TestCaseEditorMode.ViewMode)
                    {
                        htmlEditor_Desc.IsEditMode = false;
                        htmlEditor_Expected.IsEditMode = false;
                        htmlEditor_Validation.IsEditMode = false;
                    }
                    else if (PresentMode == TestCaseEditorMode.EditMode)
                    {
                        //htmlEditor_Desc.RichTextRTF = htmlEditor_Desc.GetRTFFromHTML();
                        //htmlEditor_Validation.RichTextRTF = htmlEditor_Validation.GetRTFFromHTML();
                        //htmlEditor_Expected.RichTextRTF = htmlEditor_Expected.GetRTFFromHTML();


                        htmlEditor_Desc.IsEditMode = true;
                        htmlEditor_Expected.IsEditMode = true;
                        htmlEditor_Validation.IsEditMode = true;

                    }
                    tabPage_TestCase.Text = tcid;
                    displayedID = tcid;
                    if (reviewComments.Contains(displayedID))
                    {
                        btn_RemoveReview.Enabled = true;
                        htmlEditor_Review.HTMLText = ((string[])(reviewComments[displayedID]))[1];
                    }
                    else
                    {
                        btn_RemoveReview.Enabled = false;
                        htmlEditor_Review.HTMLText = string.Empty;
                    }
                
            }
        }

        private void listView_testcases_MouseClick(object sender, MouseEventArgs e)
        {
            if (this.listView_testcases.Items.Count > 0)
            {
                if (this.listView_testcases.CheckedItems.Count < this.listView_testcases.Items.Count)
                {
                    SelectAll_checkBox.CheckState = CheckState.Unchecked;
                    SelectAll_checkBox.Enabled = true;
                }
                else
                    SelectAll_checkBox.Enabled = false;

            }
            //if (this.listView_testcases.SelectedItems.Count > 0)
            //{

            //    foreach (ListViewItem tcitem in this.listView_testcases.SelectedItems)
            //    {

            //        populateTestCaseOnForm(tcitem.SubItems[0].Text);
            //        break;

            //    }

            //}
        }

        private void listView_testcases_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.listView_testcases.SelectedItems.Count > 0)
            {

                foreach (ListViewItem tcitem in this.listView_testcases.SelectedItems)
                {

                    
                    populateTestCaseOnForm(tcitem.SubItems[0].Text);
                    SetModeOFEditor(TestCaseEditorMode.EditMode);
                    break;

                }

            }
        }

        private void SetModeOFEditor(TestCaseEditorMode Mode)
        {
            switch (Mode)
            { 
                case TestCaseEditorMode.ViewMode: {
                                                    PresentMode = TestCaseEditorMode.ViewMode;

                                                    listView_testcases.Items.Clear();
                                                    populateTestCaseList();

                                                    this.txt_name.ReadOnly = true;
                                                    
                                                    this.txt_notes.ReadOnly = true;
                                                    this.txt_objective.ReadOnly = true;

                                                    this.cmb_TestCaseMethods.DropDownStyle = ComboBoxStyle.DropDownList;
                                                    this.cmb_TestCasePackage.DropDownStyle = ComboBoxStyle.DropDownList;
                                                    this.cmb_TestCasePriority.DropDownStyle = ComboBoxStyle.DropDownList;
                                                    this.cmb_TestCaseRisks.DropDownStyle = ComboBoxStyle.DropDownList;
                                                    this.cmb_TestCaseType.DropDownStyle = ComboBoxStyle.DropDownList;

                                                    this.cmb_TestCaseType.Enabled = false;
                                                    this.cmb_TestCaseMethods.Enabled = false;
                                                    this.cmb_TestCasePriority.Enabled = false;
                                                    this.cmb_TestCaseRisks.Enabled = false;
                                                    this.cmb_TestCasePackage.Enabled = false;
                                                    this.txt_preConditions.ReadOnly = true;
                                                    this.txt_postConditions.ReadOnly = true;

                                                    ClearTestCaseOnForm();

                                                    htmlEditor_Validation.IsEditMode = false;
                                                    htmlEditor_Desc.IsEditMode = false;
                                                    htmlEditor_Expected.IsEditMode = false;
                                                    groupBox_TestCaseList.Enabled = true;
                                                    groupBox_options.Enabled = true;
                                                    tabControl_TestCase.Enabled = true;

                                                    btn_Complete.Enabled = btn_Cancel.Enabled = false;

                                                    this.Cursor = Cursors.Default;

                                                    break;
                                                 
                }

                case TestCaseEditorMode.EditMode: {
                                                    PresentMode = TestCaseEditorMode.EditMode;
                                                    this.txt_name.ReadOnly = false;
                                                    htmlEditor_Desc.IsEditMode = true;

                                                    this.txt_notes.ReadOnly = false;
                                                    this.txt_objective.ReadOnly = false;

                                                    this.cmb_TestCaseMethods.DropDownStyle = ComboBoxStyle.DropDownList;
                                                    this.cmb_TestCasePackage.DropDownStyle = ComboBoxStyle.DropDownList;
                                                    this.cmb_TestCasePriority.DropDownStyle = ComboBoxStyle.DropDownList;
                                                    this.cmb_TestCaseRisks.DropDownStyle = ComboBoxStyle.DropDownList;
                                                    this.cmb_TestCaseType.DropDownStyle = ComboBoxStyle.DropDownList;
                                                    
                                                    this.cmb_TestCaseType.Enabled = true;
                                                    this.cmb_TestCaseMethods.Enabled = true;
                                                    this.cmb_TestCasePriority.Enabled = true;
                                                    this.cmb_TestCaseRisks.Enabled = true;
                                                    this.cmb_TestCasePackage.Enabled = true;
                                                    this.txt_preConditions.ReadOnly = false;
                                                    this.txt_postConditions.ReadOnly = false;
                                                    htmlEditor_Validation.IsEditMode = true;
                                                    htmlEditor_Expected.IsEditMode = true;
                                                    groupBox_TestCaseList.Enabled = false;
                                                    groupBox_options.Enabled = false;
                                                    tabControl_TestCase.Enabled = true;
                                                    btn_Complete.Enabled = btn_Cancel.Enabled = true;
                                                    this.Cursor = Cursors.Default;
                                                    break;
                
                }
                case TestCaseEditorMode.BulkMode: {
                                                    PresentMode = TestCaseEditorMode.BulkMode;
                                                    this.txt_name.ReadOnly = false;
                                                    

                                                    this.txt_notes.ReadOnly = false;
                                                    this.txt_objective.ReadOnly = false;

                                                    this.cmb_TestCaseMethods.DropDownStyle = ComboBoxStyle.DropDown;
                                                    this.cmb_TestCasePackage.DropDownStyle = ComboBoxStyle.DropDown;
                                                    this.cmb_TestCasePriority.DropDownStyle = ComboBoxStyle.DropDown;
                                                    this.cmb_TestCaseRisks.DropDownStyle = ComboBoxStyle.DropDown;
                                                    this.cmb_TestCaseType.DropDownStyle = ComboBoxStyle.DropDown;

                                                    this.cmb_TestCaseType.Enabled = true;
                                                    this.cmb_TestCaseMethods.Enabled = true;
                                                    this.cmb_TestCasePriority.Enabled = true;
                                                    this.cmb_TestCaseRisks.Enabled = true;
                                                    this.cmb_TestCasePackage.Enabled = true;
                                                    this.txt_preConditions.ReadOnly = false;
                                                    this.txt_postConditions.ReadOnly = false;

                                                    ClearTestCaseOnForm(); 
                                                    htmlEditor_Desc.IsEditMode = true;
                                                    htmlEditor_Validation.IsEditMode = true;
                                                    htmlEditor_Expected.IsEditMode = true;
                                                    groupBox_TestCaseList.Enabled = false;
                                                    groupBox_options.Enabled = false;
                                                    tabControl_TestCase.Enabled = true;
                                                    btn_Complete.Enabled = btn_Cancel.Enabled = true;
                                                    this.Cursor = Cursors.Default;                                
                    break;
                
                
                
                
                }
            case TestCaseEditorMode.ReviewMode:{
                    this.Cursor = Cursors.Default; 
                break; 
            }
            case TestCaseEditorMode.WhileUpdate:{
                
                PresentMode = TestCaseEditorMode.WhileUpdate;
                groupBox_TestCaseList.Enabled = false;
                groupBox_options.Enabled = false;
                tabControl_TestCase.Enabled = false;
                this.Cursor = Cursors.WaitCursor;
                break;
                }
            }
           
        
        }

        private void ClearTestCaseOnForm()
        {
            this.txt_name.Text = string.Empty;
            this.txt_notes.Text = string.Empty;
            this.txt_objective.Text = string.Empty;
            this.cmb_TestCaseType.Text = string.Empty;
            this.cmb_TestCaseMethods.Text = string.Empty;
            this.cmb_TestCasePriority.Text = string.Empty;
            this.cmb_TestCaseRisks.Text = string.Empty;
            this.cmb_TestCasePackage.Text = string.Empty;
            this.txt_preConditions.Text = string.Empty;
            this.txt_postConditions.Text = string.Empty;
            this.txt_Owner.Text = string.Empty;
            
            //this.htmlEditor_Validation.RichTextRTF = string.Empty;
            //this.htmlEditor_Expected.RichTextRTF = string.Empty;
            //htmlEditor_Desc.RichTextRTF = string.Empty;

            this.htmlEditor_Validation.HTMLText = string.Empty;
            this.htmlEditor_Expected.HTMLText = string.Empty;
            htmlEditor_Desc.HTMLText = string.Empty;
            //htmlEditor_Review.RichTextRTF = string.Empty;


            tabPage_TestCase.Text = "Test Case";
            displayedID = string.Empty;
            
        }

        private TestCase GetUpdatedTestCase()
        {
            TestCase tc = new TestCase();
            tc.ID = displayedID;
            tc.Name = this.txt_name.Text;

            if (!htmlEditor_Desc.isTextEmpty())
                tc.Description = htmlEditor_Desc.HTMLText;
            else
                tc.Description = string.Empty;

            tc.Notes = this.txt_notes.Text;
            tc.Objective = this.txt_objective.Text;
            tc.Type = this.cmb_TestCaseType.Text;
            tc.Method = this.cmb_TestCaseMethods.Text;
            tc.Priority = this.cmb_TestCasePriority.Text;
            tc.Risk = this.cmb_TestCaseRisks.Text;
            tc.Package = this.cmb_TestCasePackage.Text;
            tc.PreConditions = this.txt_preConditions.Text;
            tc.PostConditions = this.txt_postConditions.Text;

            if (!htmlEditor_Validation.isTextEmpty())
                tc.ValidationInput = htmlEditor_Validation.HTMLText;
            else
                tc.ValidationInput = string.Empty;

            if (!htmlEditor_Expected.isTextEmpty())
                tc.ValidationExpectedResult = htmlEditor_Expected.HTMLText;
            else
                tc.ValidationExpectedResult = string.Empty;

            return tc;
        
        }

        //this function returns a test case after getting the values from the testcasehash
        private TestCase GetTestCaseObject(string tcid)
        {
            TestCase tcreturn = new TestCase();
            tcreturn.ID = tcid;
            tcreturn.Name = ((TestCase)(testCaseHash[tcid])).Name;
            tcreturn.Notes = ((TestCase)(testCaseHash[tcid])).Notes;
            tcreturn.Objective = ((TestCase)(testCaseHash[tcid])).Objective;
            tcreturn.Type = ((TestCase)(testCaseHash[tcid])).Type;
            tcreturn.Method = ((TestCase)(testCaseHash[tcid])).Method;
            tcreturn.Priority = ((TestCase)(testCaseHash[tcid])).Priority;
            tcreturn.Risk = ((TestCase)(testCaseHash[tcid])).Risk;
            tcreturn.Package = ((TestCase)(testCaseHash[tcid])).Package;
            tcreturn.PreConditions = ((TestCase)(testCaseHash[tcid])).PreConditions;
            tcreturn.PostConditions = ((TestCase)(testCaseHash[tcid])).PostConditions;
            tcreturn.Description = ((TestCase)(testCaseHash[tcid])).Description;
            tcreturn.ValidationInput =((TestCase)(testCaseHash[tcid])).ValidationInput;
            tcreturn.ValidationExpectedResult=((TestCase)(testCaseHash[tcid])).ValidationExpectedResult;

            return tcreturn;
        }

        private void btn_bulk_Click(object sender, EventArgs e)
        {
            if (this.listView_testcases.CheckedItems.Count > 0)
            {
                SetModeOFEditor(TestCaseEditorMode.BulkMode);
            }
            else
                MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/CreateTestCase/SelectAtLeastOneItem"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.OK, MessageBoxIcon.Information);

        }

        private void btn_revert_Click(object sender, EventArgs e)
        {
            if (this.listView_testcases.CheckedItems.Count > 0)
            {
                foreach (ListViewItem tcitem in this.listView_testcases.Items)
                {
                    if (tcitem.Checked == true)
                    {
                        if (updatedTestCases.Contains(tcitem.SubItems[0].Text))
                            updatedTestCases.Remove(tcitem.SubItems[0].Text);
                    }
                }
                populateTestCaseList();
                dataupdated = true;

            }
            else
                MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/CreateTestCase/SelectAtLeastOneItem"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.OK, MessageBoxIcon.Information);

        }

        private void SelectAll_checkBox_CheckedChanged(object sender, EventArgs e)
        {
            if (this.listView_testcases.Items.Count > 0 && SelectAll_checkBox.CheckState == CheckState.Checked)
            {
                foreach (ListViewItem tcitem in this.listView_testcases.Items)
                    tcitem.Checked = true;
                SelectAll_checkBox.Enabled = false;

            }
            else
            {
                SelectAll_checkBox.Enabled = true; ;

            }
        }

        private void deselect_checkBox_CheckedChanged(object sender, EventArgs e)
        {
            if (this.listView_testcases.Items.Count > 0 && deselect_checkBox.CheckState == CheckState.Checked)
            {
                foreach (ListViewItem tcitem in this.listView_testcases.Items)
                    tcitem.Checked = false;
                deselect_checkBox.Enabled = false;

            }
        }

        private void listView_testcases_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (this.listView_testcases.SelectedItems.Count > 0)
                {

                    foreach (ListViewItem tcitem in this.listView_testcases.SelectedItems)
                    {


                        populateTestCaseOnForm(tcitem.SubItems[0].Text);
                        SetModeOFEditor(TestCaseEditorMode.EditMode);
                        break;

                    }

                }
            }
        }

        private void listView_testcases_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            if (this.listView_testcases.Items.Count > 0)
            {
                if (this.listView_testcases.CheckedItems.Count < this.listView_testcases.Items.Count)
                {
                    SelectAll_checkBox.CheckState = CheckState.Unchecked;
                    SelectAll_checkBox.Enabled = true;
                }
                else
                    SelectAll_checkBox.Enabled = false;

            }
            if (this.listView_testcases.CheckedItems.Count > 0)
            {
                deselect_checkBox.CheckState = CheckState.Unchecked;
                deselect_checkBox.Enabled = true;
            }
            else
                deselect_checkBox.Enabled = false;
        }

        private void btn_updateTestCases_Click(object sender, EventArgs e)
        {
            try
            {

                ArrayList testcasesUpdated = new ArrayList();
                if (updatedTestCases.Count == 0)
                    MessageBox.Show("No TestCases were updated.", "Update Test Cases", MessageBoxButtons.OK, MessageBoxIcon.Information);
                else
                {
                    if (MessageBox.Show("All updated test cases shall be saved to Rally. Do you want to continue?", "Update Test Cases", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        ((RallyDesk)parent).toolStripStatusLabel.Text = "Updating Test Cases...";
                        ((RallyDesk)parent).ProgressBarMain.Style = ProgressBarStyle.Marquee;
                        ((RallyDesk)parent).ProgressBarMain.Visible = true;
                        this.Cursor = Cursors.WaitCursor;
                        SetModeOFEditor(TestCaseEditorMode.WhileUpdate);

                        Logs Newlog = new Logs();
                        Newlog.textBox_log.Text = "Test Case Update Log:" + Environment.NewLine + Environment.NewLine;

                        foreach (TestCase tc in updatedTestCases.Values)
                        {
                            TestCaseOnThread = tc;
                            Thread toRunService = new Thread(new ThreadStart(UpdateTestCaseOnThread));
                            toRunService.Start();

                            while (toRunService.IsAlive)
                            {

                                Application.DoEvents();
                            }


                            toRunService.Abort();

                            if (TestCaseUpdateResult.Length > 0)
                            {
                                Newlog.textBox_log.Text += "Test Case " + tc.ID + " : Update Failed.The following error/s occured: " + TestCaseUpdateResult + Environment.NewLine;

                            }
                            else
                            {
                                Newlog.textBox_log.Text += "Test Case " + tc.ID + " : Updated." + Environment.NewLine;
                                testcasesUpdated.Add(tc.ID);


                            }

                        }



                        Newlog.textBox_log.Text += Environment.NewLine + Convert.ToString(updatedTestCases.Count) + " Records Processed.";
                        Newlog.textBox_log.Text += Environment.NewLine + Convert.ToString(testcasesUpdated.Count) + " Test Cases were Updated." + Environment.NewLine;
                        Newlog.textBox_log.Text += "Update Complete." + Environment.NewLine;

                        foreach (string ID in testcasesUpdated)
                        {
                            testCaseHash[ID] = updatedTestCases[ID];
                            updatedTestCases.Remove(ID);
                        }

                        ((RallyDesk)parent).ProgressBarMain.Visible = false;
                        ((RallyDesk)parent).toolStripStatusLabel.Text = "Ready";
                        Newlog.ShowDialog();

                    }
                }
            }
            finally
            {
                SetModeOFEditor(TestCaseEditorMode.ViewMode);
            }
        }

        private void UpdateTestCaseOnThread()
        {
            TestCaseUpdateResult = string.Empty;
            
            if (service == null)
            {
                if (RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceType == "UseCase")
                    service = new RallyAPIUseCase(RallyDesk.url);
                else
                    service = new RallyAPIUserStory(RallyDesk.url);
            }


            TestCaseUpdateResult = service.UpdateTestCase(TestCaseOnThread);
        }
        private void DeleteTestCaseOnThread()
        {
            testCaseDeleteResult = string.Empty;

            if (service == null)
            {
                if (RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceType == "UseCase")
                    service = new RallyAPIUseCase(RallyDesk.url);
                else
                    service = new RallyAPIUserStory(RallyDesk.url);
            }


            testCaseDeleteResult = service.DeleteTestCase(testCaseToDeleteID);
        }

        private void GUITestCaseEditor_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (PresentMode == TestCaseEditorMode.WhileUpdate)
            {
                MessageBox.Show("The Review/Edit Test Case cannot be closed. Review/Edit Test Case is busy...", "Review/Edit Test Case", MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Cancel = true;
            }
            else if (dataupdated)
            {
                if (MessageBox.Show("There is unsaved information on the form. All Changes shall be lost. Do you want to Continue?", "Review/Edit Test Case", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                e.Cancel = true;
            }
        }

        private void btn_loadTemplate_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                DialogResult res = new DialogResult();


                if (listView_testcases.Items.Count > 0)
                {
                    if (updatedTestCases.Count > 0)
                    {

                        res = MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/UnsavedTemplate"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                        if (res == DialogResult.Yes)
                            btn_save.PerformClick();
                        else if (res == DialogResult.Cancel)
                            return;
                    }
                }
                string msConn;
                listView_testcases.Items.Clear();
                testCaseHash.Clear();
                updatedTestCases.Clear();
                reviewComments.Clear();

                this.RecNum_label.Text = Convert.ToString(listView_testcases.Items.Count);
                this.Text = "Review/Edit Test Case";
                filename = null;


                OpenFileDialog op1 = new OpenFileDialog();
                op1.DefaultExt = ".xls";
                op1.Filter = "Excel(*.xls)|*.xls";

                
                if (op1.ShowDialog() == DialogResult.OK)
                {
                    filename = op1.FileName;
                    op1.Dispose();
                    msConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filename + ";" + "Extended Properties=\"Excel 8.0;HDR=YES\"";


                     OleDbConnection conn = new OleDbConnection();
                    conn.ConnectionString = msConn;
                    conn.Open();

                    System.Data.OleDb.OleDbCommand cmd = new OleDbCommand("Select * From [test$]", conn);
                    OleDbDataReader rdr = cmd.ExecuteReader();
                    
                    while (rdr.Read())
                    {
                        TestCase tc = new TestCase();

                        if (rdr.GetValue(0) != System.DBNull.Value)
                            tc.ID = (rdr.GetString(0));
                        else
                            tc.ID = "";

                        if (rdr.GetValue(1) != System.DBNull.Value)
                           tc.Name = (rdr.GetString(1));
                        else
                            tc.Name = "";


                        if (rdr.GetValue(2) != System.DBNull.Value)
                            tc.Description = (rdr.GetString(2));
                        else
                            tc.Description = "";

                        if (rdr.GetValue(3) != System.DBNull.Value)
                            tc.Notes= (rdr.GetString(3));
                        else
                            tc.Notes = "";

                        if (rdr.GetValue(4) != System.DBNull.Value)
                            tc.Objective = (rdr.GetString(4));
                        else
                            tc.Objective = "";

                        if (rdr.GetValue(5) != System.DBNull.Value)
                            tc.Type = (rdr.GetString(5));
                        else
                            tc.Type = "";

                        if (rdr.GetValue(6) != System.DBNull.Value)
                            tc.Method = (rdr.GetString(6));
                        else
                            tc.Method = "";

                        if (rdr.GetValue(7) != System.DBNull.Value)
                            tc.Priority = (rdr.GetString(7));
                        else
                            tc.Priority = "";

                        if (rdr.GetValue(8) != System.DBNull.Value)
                            tc.Risk = (rdr.GetString(8));
                        else
                            tc.Risk = "";

                        if (rdr.GetValue(9) != System.DBNull.Value)
                            tc.Package = (rdr.GetString(9));
                        else
                            tc.Package = "";

                        if (rdr.GetValue(10) != System.DBNull.Value)
                            tc.PreConditions = (rdr.GetString(10));
                        else
                            tc.PreConditions = "";
                        
                        if (rdr.GetValue(11) != System.DBNull.Value)
                            tc.PostConditions = (rdr.GetString(11));
                        else
                            tc.PostConditions = "";

                        if (rdr.GetValue(12) != System.DBNull.Value)
                            tc.ValidationInput = (rdr.GetString(12));
                        else
                            tc.ValidationInput = "";

                        if (rdr.GetValue(13) != System.DBNull.Value)
                            tc.ValidationExpectedResult = (rdr.GetString(13));
                        else
                            tc.ValidationExpectedResult = "";

                        if (rdr.GetValue(14) != System.DBNull.Value)
                            tc.TestRef = (rdr.GetString(14));
                        else
                            tc.TestRef = "";



                        testCaseHash.Add(tc.ID, tc);


                    }
                    rdr.Close();
                    
                    //Fetching Updated test cases

                    cmd.CommandText = ("Select * From [updatedTestCases$]");
                    OleDbDataReader rdrUpdatedTcs = cmd.ExecuteReader();
                    while (rdrUpdatedTcs.Read())
                    {
                        TestCase tcUpdated = new TestCase();

                        if (rdrUpdatedTcs.GetValue(0) != System.DBNull.Value)
                            tcUpdated.ID = (rdrUpdatedTcs.GetString(0));
                        else
                            tcUpdated.ID = "";

                        if (rdrUpdatedTcs.GetValue(1) != System.DBNull.Value)
                            tcUpdated.Name = (rdrUpdatedTcs.GetString(1));
                        else
                            tcUpdated.Name = "";


                        if (rdrUpdatedTcs.GetValue(2) != System.DBNull.Value)
                            tcUpdated.Description = (rdrUpdatedTcs.GetString(2));
                        else
                            tcUpdated.Description = "";

                        if (rdrUpdatedTcs.GetValue(3) != System.DBNull.Value)
                            tcUpdated.Notes = (rdrUpdatedTcs.GetString(3));
                        else
                            tcUpdated.Notes = "";

                        if (rdrUpdatedTcs.GetValue(4) != System.DBNull.Value)
                            tcUpdated.Objective = (rdrUpdatedTcs.GetString(4));
                        else
                            tcUpdated.Objective = "";

                        if (rdrUpdatedTcs.GetValue(5) != System.DBNull.Value)
                            tcUpdated.Type = (rdrUpdatedTcs.GetString(5));
                        else
                            tcUpdated.Type = "";

                        if (rdrUpdatedTcs.GetValue(6) != System.DBNull.Value)
                            tcUpdated.Method = (rdrUpdatedTcs.GetString(6));
                        else
                            tcUpdated.Method = "";

                        if (rdrUpdatedTcs.GetValue(7) != System.DBNull.Value)
                            tcUpdated.Priority = (rdrUpdatedTcs.GetString(7));
                        else
                            tcUpdated.Priority = "";

                        if (rdrUpdatedTcs.GetValue(8) != System.DBNull.Value)
                            tcUpdated.Risk = (rdrUpdatedTcs.GetString(8));
                        else
                            tcUpdated.Risk = "";

                        if (rdrUpdatedTcs.GetValue(9) != System.DBNull.Value)
                            tcUpdated.Package = (rdrUpdatedTcs.GetString(9));
                        else
                            tcUpdated.Package = "";

                        if (rdrUpdatedTcs.GetValue(10) != System.DBNull.Value)
                            tcUpdated.PreConditions = (rdrUpdatedTcs.GetString(10));
                        else
                            tcUpdated.PreConditions = "";

                        if (rdrUpdatedTcs.GetValue(11) != System.DBNull.Value)
                            tcUpdated.PostConditions = (rdrUpdatedTcs.GetString(11));
                        else
                            tcUpdated.PostConditions = "";

                        if (rdrUpdatedTcs.GetValue(12) != System.DBNull.Value)
                            tcUpdated.ValidationInput = (rdrUpdatedTcs.GetString(12));
                        else
                            tcUpdated.ValidationInput = "";

                        if (rdrUpdatedTcs.GetValue(13) != System.DBNull.Value)
                            tcUpdated.ValidationExpectedResult = (rdrUpdatedTcs.GetString(13));
                        else
                            tcUpdated.ValidationExpectedResult = "";

                        if (rdrUpdatedTcs.GetValue(14) != System.DBNull.Value)
                            tcUpdated.TestRef = (rdrUpdatedTcs.GetString(14));
                        else
                            tcUpdated.TestRef = "";



                        updatedTestCases.Add(tcUpdated.ID, tcUpdated);


                    }

                    rdrUpdatedTcs.Close();
                    //fetching updated test cases done

                    //fetching reviews
                    cmd.CommandText = ("Select * From [review$]");
                    OleDbDataReader rdr2 = cmd.ExecuteReader();
                    while (rdr2.Read())
                    {
                        string[] rCom = new string[2];

                        if (rdr2.GetValue(0) != System.DBNull.Value)
                            rCom[0] = (rdr2.GetString(0));
                        else
                            rCom[0] = "";

                        if (rdr2.GetValue(1) != System.DBNull.Value)
                            rCom[1] = (rdr2.GetString(1));
                        else
                            rCom[1] = "";

                        reviewComments.Add(rCom[0], rCom);
                    }
                    // fetching reviews done


                  
                    

                    this.RecNum_label.Text = Convert.ToString(testCaseHash.Count);
                    this.Text = "Review/Edit Test Case-(" + filename + ")";

                    rdr2.Close();
                    
                    msConn = null;
                    conn.Close();
                    conn = null;

                }
            }
            catch (System.IndexOutOfRangeException)
            {

                MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/InvalidTemplate"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (System.Data.OleDb.OleDbException)
            {

                MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/InvalidTemplate"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
            catch (Exception)
            {
                throw;
            }

            finally
            {
                
                
                this.Cursor = Cursors.Default;
                this.SetModeOFEditor(TestCaseEditorMode.ViewMode);
            }
        }

        private void btn_closeTemplate_Click(object sender, EventArgs e)
        {
            if (updatedTestCases.Count > 0)
            {
                DialogResult res = new DialogResult();
                res = MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/SaveChanges"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
                if (res == DialogResult.Yes)
                {
                    btn_save.PerformClick();
                }
                if (res == DialogResult.Cancel)
                    return;

            }
            close_Template();

            this.RecNum_label.Text = Convert.ToString(testCaseHash.Count);
            this.Text = "Review/Edit Test Case";
            filename = null;

        }
        private void close_Template()
        {
            listView_testcases.Items.Clear();
            testCaseHash.Clear();
            updatedTestCases.Clear();
            reviewComments.Clear();
        }
        private void btn_save_Click(object sender, EventArgs e)
        {
            try
            {
                if (testCaseHash.Count > 0)
                {
                    Rally_Dekstop.Program.RallyMain.toolStripStatusLabel.Text = "Saving...";
                    string msConn;
                    if (filename == null || saveAsFlag)
                    {
                        SaveFileDialog op1 = new SaveFileDialog();
                        op1.DefaultExt = ".xls";
                        op1.Filter = "Excel(*.xls)|*.xls";
                        if (op1.ShowDialog() != DialogResult.Cancel)
                        {
                            filename = op1.FileName;
                            if (filename == string.Empty)
                                filename = null;
                            op1.Dispose();
                        }
                        else
                            return;
                    }
                    if (filename != null)
                    {

                        if (System.IO.File.Exists(filename))
                        {
                            System.IO.File.Delete(filename);
                        }

                        msConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filename + ";" + "Extended Properties=\"Excel 8.0;HDR=YES\"";

                        //DataViewer NewData = new DataViewer();
                        OleDbConnection conn = new OleDbConnection();
                        conn.ConnectionString = msConn;
                        conn.Open();


                        System.Data.OleDb.OleDbCommand cmd = new OleDbCommand("CREATE TABLE test " + "([ID] TEXT(255),[Name] TEXT(255),[Description] LONGTEXT,[Notes] LONGTEXT,[Objective] LONGTEXT, [Type] TEXT(100),[Methods] TEXT(100),[Priority] TEXT(100),[Risk] TEXT(100),[Package] TEXT(100),[PreConditions] LONGTEXT,[PostConditions] LONGTEXT,[ValidationInput] LONGTEXT,[ExpectedResult] LONGTEXT,[TestCaseRef] TEXT(255))", conn);
                        string str;
                        cmd.ExecuteNonQuery();
                        foreach (TestCase tc in testCaseHash.Values)
                        {
                            str = ("INSERT INTO test VALUES ('" + tc.ID.Replace("'", "''") + 
                                "','" + tc.Name.Replace("'", "''") + 
                                "','" + tc.Description.Replace("'", "''") + 
                                "','" + tc.Notes.Replace("'", "''") + 
                                "','" + tc.Objective.Replace("'", "''") +
                                "','" + tc.Type.Replace("'", "''") +
                                "','" + tc.Method.Replace("'", "''") +
                                "','" + tc.Priority.Replace("'", "''") + 
                                "','" + tc.Risk.Replace("'", "''") +
                                "','" + tc.Package.Replace("'", "''") +
                                "','" + tc.PreConditions.Replace("'", "''") +
                                "','" + tc.PostConditions.Replace("'", "''") +
                                "','" + tc.ValidationInput.Replace("'", "''") + 
                                "','" + tc.ValidationExpectedResult.Replace("'", "''") +
                                "','" + tc.TestRef.Replace("'", "''") + "')");
                            cmd.CommandText = str;
                            cmd.ExecuteNonQuery();

                        }
                        //storing Updated Test Cases
                        cmd.CommandText = ("CREATE TABLE updatedTestCases " + "([ID] TEXT(255),[Name] TEXT(255),[Description] LONGTEXT,[Notes] LONGTEXT,[Objective] LONGTEXT, [Type] TEXT(100),[Methods] TEXT(100),[Priority] TEXT(100),[Risk] TEXT(100),[Package] TEXT(100),[PreConditions] LONGTEXT,[PostConditions] LONGTEXT,[ValidationInput] LONGTEXT,[ExpectedResult] LONGTEXT,[TestCaseRef] TEXT(255))");
                        cmd.ExecuteNonQuery();
                        foreach (TestCase tcUpdated in updatedTestCases.Values)
                        {
                            cmd.CommandText = ("INSERT INTO updatedTestCases VALUES ('" + tcUpdated.ID.Replace("'", "''") +
                                "','" + tcUpdated.Name.Replace("'", "''") +
                                "','" + tcUpdated.Description.Replace("'", "''") +
                                "','" + tcUpdated.Notes.Replace("'", "''") +
                                "','" + tcUpdated.Objective.Replace("'", "''") +
                                "','" + tcUpdated.Type.Replace("'", "''") +
                                "','" + tcUpdated.Method.Replace("'", "''") +
                                "','" + tcUpdated.Priority.Replace("'", "''") +
                                "','" + tcUpdated.Risk.Replace("'", "''") +
                                "','" + tcUpdated.Package.Replace("'", "''") +
                                "','" + tcUpdated.PreConditions.Replace("'", "''") +
                                "','" + tcUpdated.PostConditions.Replace("'", "''") +
                                "','" + tcUpdated.ValidationInput.Replace("'", "''") +
                                "','" + tcUpdated.ValidationExpectedResult.Replace("'", "''") +
                                "','" + tcUpdated.TestRef.Replace("'", "''") + "')");
                            cmd.ExecuteNonQuery();

                        }
                        //Saved updatedtest cases list


                        //storing reviews
                        cmd.CommandText = ("CREATE TABLE review " + "([ID] TEXT(255),[ReviewComments] LONGTEXT)");
                        cmd.ExecuteNonQuery();

                        foreach (string[] RComment in reviewComments.Values)
                        {
                            cmd.CommandText = ("INSERT INTO review VALUES ('" + RComment[0].Replace("'", "''") +
                                "','" + RComment[1].Replace("'", "''") + "')");
                            cmd.ExecuteNonQuery();

                        }

                        msConn = null;
                        conn.Close();
                        conn = null;

                        dataupdated = false;
                        this.Text = "Review/Edit Test Case-[" + filename + "]";
                        Rally_Dekstop.Program.RallyMain.toolStripStatusLabel.Text = "Saved.";
                        MessageBox.Show("Template Saved.", "Rally Desk",MessageBoxButtons.OK,MessageBoxIcon.Information);
                       
                    }
                }

            }
            catch (System.IndexOutOfRangeException)
            {

                MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/InvalidTemplate"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (System.Data.OleDb.OleDbException)
            {

                MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/InvalidTemplate"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
            catch (Exception)
            {
                throw;
            }


            finally
            {

                saveAsFlag = false;
                Rally_Dekstop.Program.RallyMain.toolStripStatusLabel.Text = "Ready";
                this.SetModeOFEditor(TestCaseEditorMode.ViewMode);
            }
        }

        private void btn_SaveAS_Click(object sender, EventArgs e)
        {
            saveAsFlag = true;
            this.btn_save.PerformClick();

        }

        private void tabControl_TestCase_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl_TestCase.SelectedTab.Text == "Review Comments")
                if (!testCaseHash.Contains(displayedID))
                {
                    MessageBox.Show("Please select test case to add review comments.", "Rally Desk", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    tabControl_TestCase.SelectTab(tabPage_TestCase);
                }

        }

        private void btn_AddReview_Click(object sender, EventArgs e)
        {
            if (!htmlEditor_Review.isTextEmpty())
            {
                string[] rComment = new string[2];
                rComment[0] = displayedID;
                rComment[1] = htmlEditor_Review.HTMLText;

                if (reviewComments.Contains(displayedID))
                {
                    
                       
                        reviewComments[displayedID] = rComment;
                   
                }
                else
                {
                   
                        reviewComments.Add(displayedID, rComment);
                }
                populateTestCaseList();
                htmlEditor_Review.HTMLText = string.Empty;
                tabControl_TestCase.SelectTab(tabPage_TestCase);
                dataupdated = true;

            }
        }

        private void btn_RemoveReview_Click(object sender, EventArgs e)
        {
            if (reviewComments.Contains(displayedID))
            {
               reviewComments.Remove(displayedID);
               populateTestCaseList();
               dataupdated = true;
            }
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            SetModeOFEditor(TestCaseEditorMode.ViewMode);


        }

        private void btn_Complete_Click_1(object sender, EventArgs e)
        {
            TestCase tc = GetUpdatedTestCase();
            dataupdated = true;
            switch (PresentMode)
            {
                case TestCaseEditorMode.EditMode: {

                   
                    if (updatedTestCases.Contains(tc.ID))
                    {
                        updatedTestCases[tc.ID] = tc;
                        ((TestCase)(updatedTestCases[tc.ID])).TestRef = ((TestCase)(testCaseHash[tc.ID])).TestRef;
                    }
                    else
                    {
                        updatedTestCases.Add(tc.ID, tc);
                        ((TestCase)(updatedTestCases[tc.ID])).TestRef = ((TestCase)(testCaseHash[tc.ID])).TestRef;
                    }

                    SetModeOFEditor(TestCaseEditorMode.ViewMode);
                    break;

                }
                case TestCaseEditorMode.BulkMode: {

                    TestCase tcObj = new TestCase();
                    if (tc.ID == string.Empty)
                    {
                        foreach (ListViewItem tcitem in this.listView_testcases.Items)
                        {
                            if (tcitem.Checked == true)
                            {

                                if (!updatedTestCases.Contains(tcitem.SubItems[0].Text))
                                {
                                    tcObj = GetTestCaseObject(tcitem.SubItems[0].Text);
                                    updatedTestCases.Add(tcitem.SubItems[0].Text, tcObj);
                                    ((TestCase)(updatedTestCases[tcitem.SubItems[0].Text])).TestRef = ((TestCase)(testCaseHash[tcitem.SubItems[0].Text])).TestRef;
                                }

                               if(tc.Name != string.Empty)
                                    ((TestCase)(updatedTestCases[tcitem.SubItems[0].Text])).Name = tc.Name;

                                if (tc.Notes != string.Empty)
                                    ((TestCase)(updatedTestCases[tcitem.SubItems[0].Text])).Notes = tc.Notes;

                                if (tc.Objective != string.Empty)
                                    ((TestCase)(updatedTestCases[tcitem.SubItems[0].Text])).Objective = tc.Objective;

                                if (tc.Type != string.Empty)
                                    ((TestCase)(updatedTestCases[tcitem.SubItems[0].Text])).Type = tc.Type;

                                if (tc.Method != string.Empty)
                                    ((TestCase)(updatedTestCases[tcitem.SubItems[0].Text])).Method = tc.Method;

                                if (tc.Priority != string.Empty)
                                    ((TestCase)(updatedTestCases[tcitem.SubItems[0].Text])).Priority = tc.Priority;

                                if (tc.Risk != string.Empty)
                                    ((TestCase)(updatedTestCases[tcitem.SubItems[0].Text])).Risk = tc.Risk;

                                if (tc.Package != string.Empty)
                                    ((TestCase)(updatedTestCases[tcitem.SubItems[0].Text])).Package = tc.Package;

                                if (tc.PreConditions != string.Empty)
                                    ((TestCase)(updatedTestCases[tcitem.SubItems[0].Text])).PreConditions = tc.PreConditions;

                                if (tc.PostConditions != string.Empty)
                                    ((TestCase)(updatedTestCases[tcitem.SubItems[0].Text])).PostConditions = tc.PostConditions;

                                if (tc.Description != string.Empty)
                                    ((TestCase)(updatedTestCases[tcitem.SubItems[0].Text])).Description = tc.Description;

                                if (tc.ValidationInput != string.Empty)
                                    ((TestCase)(updatedTestCases[tcitem.SubItems[0].Text])).ValidationInput = tc.ValidationInput;

                                if (tc.ValidationExpectedResult != string.Empty)
                                    ((TestCase)(updatedTestCases[tcitem.SubItems[0].Text])).ValidationExpectedResult = tc.ValidationExpectedResult;
                            }
                        }
                    }
                    SetModeOFEditor(TestCaseEditorMode.ViewMode);
                    break;
                }
        }
             
        
        }

        private void listView_testcases_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            if (e.Column == 0)
                if (listView_testcases.Sorting == SortOrder.Ascending)
                    listView_testcases.Sorting = SortOrder.Descending;
                else
                    listView_testcases.Sorting = SortOrder.Ascending;
        }

        private void btn_SaveAsText_Click(object sender, EventArgs e)
        {
            try
            {
                if (testCaseHash.Count > 0)
                {
                   
                    string msConn;
                    int count = 1;
                    string newFile;
                        SaveFileDialog op1 = new SaveFileDialog();
                        op1.DefaultExt = ".xls";
                        op1.Filter = "Excel(*.xls)|*.xls";
                        if (op1.ShowDialog() != DialogResult.Cancel)
                        {
                            newFile = op1.FileName;
                            if (newFile == string.Empty)
                                newFile = null;
                            op1.Dispose();
                        }
                        else
                            return;

                        if (!string.IsNullOrEmpty(newFile))
                        {
                             Rally_Dekstop.Program.RallyMain.toolStripStatusLabel.Text = "Saving...";
                             Rally_Dekstop.Program.RallyMain.ProgressBarMain.Style = ProgressBarStyle.Blocks;
                             Rally_Dekstop.Program.RallyMain.ProgressBarMain.Maximum = testCaseHash.Count;
                             Rally_Dekstop.Program.RallyMain.ProgressBarMain.Step = 1;
                             Rally_Dekstop.Program.RallyMain.ProgressBarMain.Visible = true;

                             Application.DoEvents();

                        if (System.IO.File.Exists(newFile))
                        {
                            System.IO.File.Delete(newFile);
                        }
                        //RTFConvertor.Convertor converter = new RTFConvertor.Convertor();
                        msConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + newFile + ";" + "Extended Properties=\"Excel 8.0;HDR=YES\"";

                        //DataViewer NewData = new DataViewer();
                        OleDbConnection conn = new OleDbConnection();
                        conn.ConnectionString = msConn;
                        conn.Open();


                        System.Data.OleDb.OleDbCommand cmd = new OleDbCommand("CREATE TABLE testCases " + "([ID] TEXT(255),[Name] TEXT(255),[Description] LONGTEXT,[Notes] LONGTEXT,[Objective] LONGTEXT, [Type] TEXT(100),[Methods] TEXT(100),[Priority] TEXT(100),[Risk] TEXT(100),[Package] TEXT(100),[PreConditions] LONGTEXT,[PostConditions] LONGTEXT,[ValidationInput] LONGTEXT,[ExpectedResult] LONGTEXT,[TestCaseRef] TEXT(255))", conn);
                        string str;
                        cmd.ExecuteNonQuery();

                        foreach (TestCase tc in testCaseHash.Values)
                        {
                            Rally_Dekstop.Program.RallyMain.toolStripStatusLabel.Text = "Saving " + count + " of " + testCaseHash.Count;
                            Rally_Dekstop.Program.RallyMain.ProgressBarMain.PerformStep();
                            Application.DoEvents();

                            str = ("INSERT INTO testCases VALUES ('" + tc.ID.Replace("'", "''") +
                                "','" + tc.Name.Replace("'", "''") +
                                "','" + Utilities.HtmlParser("body",tc.Description,HtmlParserOption.Inner_Text).Replace("'", "''") +
                                "','" + tc.Notes.Replace("'", "''") +
                                "','" + tc.Objective.Replace("'", "''") +
                                "','" + tc.Type.Replace("'", "''") +
                                "','" + tc.Method.Replace("'", "''") +
                                "','" + tc.Priority.Replace("'", "''") +
                                "','" + tc.Risk.Replace("'", "''") +
                                "','" + tc.Package.Replace("'", "''") +
                                "','" + tc.PreConditions.Replace("'", "''") +
                                "','" + tc.PostConditions.Replace("'", "''") +
                                "','" + Utilities.HtmlParser("body", tc.ValidationInput,HtmlParserOption.Inner_Text).Replace("'", "''") +
                                "','" + Utilities.HtmlParser("body", tc.ValidationExpectedResult,HtmlParserOption.Inner_Text).Replace("'", "''") +
                                "','" + tc.TestRef.Replace("'", "''") + "')");
                            cmd.CommandText = str;
                            cmd.ExecuteNonQuery();
                            count++;
                            
                        }
                                             

                        msConn = null;
                        conn.Close();
                        conn = null;

                        dataupdated = false;
                        this.Text = "Review/Edit Test Case-[" + newFile + "]";
                        Rally_Dekstop.Program.RallyMain.toolStripStatusLabel.Text = "Saved.";
                        MessageBox.Show("Template Saved.", "Rally Desk", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    }
                }

            }
            catch (System.IndexOutOfRangeException)
            {

                MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/InvalidTemplate"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (System.Data.OleDb.OleDbException)
            {

                MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/InvalidTemplate"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
            catch (Exception)
            {
                throw;
            }


            finally
            {

                //saveAsFlag = false;
                Rally_Dekstop.Program.RallyMain.toolStripStatusLabel.Text = "Ready";
                Rally_Dekstop.Program.RallyMain.ProgressBarMain.Visible = false;
                this.SetModeOFEditor(TestCaseEditorMode.ViewMode);
            }
        }

        private void btn_DeleteInRally_Click(object sender, EventArgs e)
        {
            try
            {

                ArrayList testcasesDeleted = new ArrayList();
                if (this.listView_testcases.CheckedItems.Count == 0)
                    MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/CreateTestCase/SelectAtLeastOneItem"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                else
                {
                    if (MessageBox.Show("All selected test cases shall be deleted from Rally. Do you want to continue?", "Delete Test Cases", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        ((RallyDesk)parent).toolStripStatusLabel.Text = "Deleting Test Cases...";
                        ((RallyDesk)parent).ProgressBarMain.Style = ProgressBarStyle.Marquee;
                        ((RallyDesk)parent).ProgressBarMain.Visible = true;
                        this.Cursor = Cursors.WaitCursor;
                        SetModeOFEditor(TestCaseEditorMode.WhileUpdate);

                        Logs Newlog = new Logs();
                        Newlog.textBox_log.Text = "Test Case Delete Log:" + Environment.NewLine + Environment.NewLine;


                        foreach (ListViewItem tcitem in this.listView_testcases.Items)
                        {
                            if (tcitem.Checked == true)
                            {
                                if (testCaseHash.Contains(tcitem.SubItems[0].Text))
                                {
                                    testCaseToDeleteID = tcitem.SubItems[0].Text;

                                    Thread toRunService = new Thread(new ThreadStart(DeleteTestCaseOnThread));
                                    toRunService.Start();

                                    while (toRunService.IsAlive)
                                    {

                                        Application.DoEvents();
                                    }
                                    
                                    toRunService.Abort();
                                    if (testCaseDeleteResult.Length > 0)
                                    {
                                        Newlog.textBox_log.Text += "Test Case " + testCaseToDeleteID + " : Deleting Failed.The following error/s occured: " + testCaseDeleteResult + Environment.NewLine;
                                    }
                                    else
                                    {
                                        Newlog.textBox_log.Text += "Test Case " + testCaseToDeleteID + " : Deleted." + Environment.NewLine;
                                        testcasesDeleted.Add(testCaseToDeleteID);
                                    }

                                }

                            }

                        }


                        Newlog.textBox_log.Text += Environment.NewLine + Convert.ToString(listView_testcases.CheckedItems.Count) + " Records Processed.";
                        Newlog.textBox_log.Text += Environment.NewLine + Convert.ToString(testcasesDeleted.Count) + " Test Cases were Deleted." + Environment.NewLine;
                        Newlog.textBox_log.Text += "Deletion Complete." + Environment.NewLine;

                        foreach (string ID in testcasesDeleted)
                        {
                            testCaseHash.Remove(ID);
                        }

                        ((RallyDesk)parent).ProgressBarMain.Visible = false;
                        ((RallyDesk)parent).toolStripStatusLabel.Text = "Ready";
                        Newlog.ShowDialog();

                    }
                }
            }
            finally
            {
                SetModeOFEditor(TestCaseEditorMode.ViewMode);
            }
        }

      }
}